package com.justech.mes.utils;

import com.beust.jcommander.internal.Lists;
import com.justech.mes.v2.model.dto.ShortInterval;

import java.util.Date;
import java.util.List;

import static com.justech.mes.utils.DateUtil.SHORT_FORMAT;

/**
 * @author feifei.li
 */
public class TimeCutting {
    public static final String MONTH = "M";
    /**
     * 每天的最后一毫秒
     **/
    public static final Long DAY_LASTMILLI_SECOND = 86400000L;

    /**
     * 切割時間段
     *
     * @param start yyyy-MM-dd HH:mm:ss
     * @param end   yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static List<ShortInterval> cutSlotToPoint(Date start, Date end) {
        String prefix = DateUtil.splitTime(start);
        String suffix = DateUtil.splitTime(end);
        List<String> days = DateUtil.getDays(start, end);
        List<ShortInterval> intervals = Lists.newArrayList();
        for (int i = 0; i < days.size(); i++) {
            Long iStart = 0L;
            Long iEnd = 0L;
            if (i == 0) {
                /*第一个天的日期开始就是时间片的开始时间；
                 * 结束时间为当天的最后一点*/
                iStart = DateUtil.parseStamp(prefix, SHORT_FORMAT);
                if (days.size() == 1) {
                    iEnd = DateUtil.parseStamp(suffix, SHORT_FORMAT);
                } else {
                    iEnd = DAY_LASTMILLI_SECOND;
                }
            } else if (i == (days.size() - 1)) {
                iStart = 0L;
                /* 区间的结束时间点就是最后一片时间的结束点 */
                iEnd = DateUtil.parseStamp(suffix, SHORT_FORMAT);
            } else {
                /*处于中间的时间片的开始和结束是每天的第一和最后一毫秒*/
                iStart = 0L;
                iEnd = DAY_LASTMILLI_SECOND;
            }
            ShortInterval interval = new ShortInterval(iStart, iEnd);
            intervals.add(interval);
        }
        return intervals;
    }

    public static List<ShortInterval> cutSlotToPoint(String start, String end) {
        return cutSlotToPoint(DateUtil.parse(start), DateUtil.parse(end));
    }

    public static void main(String[] args) {
        String start = "2019-07-15 09:09:00";
        String end = "2019-07-17 07:59:00";
        List<ShortInterval> shortIntervals = TimeCutting.cutSlotToPoint(start, end);

        shortIntervals.stream().forEach(e -> {
            System.out.println(e.toString());
        });
    }
}
